import random,socket,subprocess,webview

def get_unused_port():
    """获取未被使用的端口"""
    while True:
        port = random.randint(1024, 65535)  # 端口范围一般为1024-65535
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.bind(("localhost", port))
            sock.close()
            return port
        except OSError:
            pass

def start_django_server(port=8000):
    # Start the Django development server in a new process.
    server_process = subprocess.Popen(
        ['python', 'manage.py', 'runserver', f'0.0.0.0:{port}'],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,  # Redirect stderr to stdout
        text=True,                 # Use text mode for the pipes
        bufsize=1                  # Line-buffered
    )

    # Function to read and print output from the process
    def print_output(process):
        for line in process.stdout:
            print(line, end='')

    import threading
    # Start a thread to read and print the output
    output_thread = threading.Thread(target=print_output, args=(server_process,))
    output_thread.daemon = True  # Thread will close when the main program exits
    output_thread.start()

    return server_process

port=get_unused_port()
# Start the server on port 8000
server = start_django_server(port)
print('Run server at port:',port)
# 在PyWebview应用程序中加载FastAPI应用程序的URL
window=webview.create_window('数字档案管理系统', f'http://localhost:{port}/admin')
def maximize_window():
    # 获取窗口对象并最大化
    window.maximize()

webview.start(maximize_window)

# Later, to stop the server:
server.terminate()
server.wait()